package com.medicine.controller.admin;

import com.medicine.dto.MedicineDTO;
import com.medicine.result.Result;
import com.medicine.service.MedicineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 药品管理
 */
@RestController
@RequestMapping("/admin/medicine")
@Api(tags = "药品相关接口")
@Slf4j
public class MedicineController {

    @Autowired
    private MedicineService medicineService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增药品
     *
     * @param medicineDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增药品")
    public Result save(@RequestBody MedicineDTO medicineDTO) {
        log.info("新增药品：{}", medicineDTO);
        medicineService.save(medicineDTO);

        //清理缓存数据
        String key = "all_medicines";
        cleanCache(key);
        return Result.success();
    }


    /**
     * 药品批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("药品批量删除")
    public Result delete(@RequestParam List<Long> ids) {
        log.info("药品批量删除：{}", ids);
        medicineService.deleteBatch(ids);

        //将所有的药品缓存数据清理掉，所有以medicine_开头的key
        cleanCache("medicine_*");

        return Result.success();
    }

    

    /**
     * 修改药品
     *
     * @param medicineDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改药品")
    public Result update(@RequestBody MedicineDTO medicineDTO) {
        log.info("修改药品：{}", medicineDTO);
        medicineService.update(medicineDTO);

        //将所有的药品缓存数据清理掉，所有以medicine_开头的key
        cleanCache("medicine_*");

        return Result.success();
    }

    /**
     * 药品起售停售
     *
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("药品起售停售")
    public Result<String> startOrStop(@PathVariable Integer status, Long id) {
        medicineService.startOrStop(status, id);

        //将所有的药品缓存数据清理掉，所有以medicine_开头的key
        cleanCache("medicine_*");

        return Result.success();
    }


    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
